#include "alone_key.h"
#include "at24c02.h"
#include "c51.h"
// #include "ds18b20.h"
#include "interrupt.h"
// #include "lcd1602.h"
#include "nixie_tube.h"
#include "utils.h"

u8 key;
_Bool flag = false;
u8 minute, second, ms;

void stop_watch_reset(void) { minute = 0, second = 0, ms = 0; }
void persist(void) {
  at24c02_write(0, minute);
  delay(5);
  at24c02_write(1, second);
  delay(5);
  at24c02_write(2, ms);
  delay(5);
}

int main(void) {
  interrupt_timer0_init(interrupt_timer0_1ms_reset);
  // ds18b20_convert();
  // delay(1);
  // f32 temperature;
  // lcd_init();
  // lcd_show_string(1, 1, "Temperature:");

  while (true) {
    key = alone_key_get();
    if (key == 1) {
      // ++num;
      flag = !flag;
    } else if (key == 2) {
      // --num;
      stop_watch_reset();
    } else if (key == 3) {
      persist();
    } else if (key == 4) {
      minute = at24c02_read(0);
      second = at24c02_read(1);
      ms = at24c02_read(2);
    }
    nixie_tube_set(8, minute / 10);
    nixie_tube_set(7, minute % 10);
    nixie_tube_set(6, Bar);
    nixie_tube_set(5, second / 10);
    nixie_tube_set(4, second % 10);
    nixie_tube_set(3, Bar);
    nixie_tube_set(2, ms / 10);
    nixie_tube_set(1, ms % 10);
  }
  return 0;
}

void stop_watch_loop(void) {
  if (flag) {
    ++ms;
    if (ms > 99) {
      ms = 0;
      ++second;
      if (second > 59) {
        second = 0;
        ++minute;
        if (minute > 59) {
          minute = 0;
        }
      }
    }
  }
}

void timer0() __interrupt(1) {
  static u16 count, cnt, ct;

  interrupt_timer0_1ms_reset();
  ++count;
  if (count > 19) {
    count = 0;
    alone_key_loop();
  }

  cnt++;
  if (cnt > 1) {
    cnt = 0;
    nixie_tube_loop();
  }

  ++ct;
  if (ct > 9) {
    ct = 0;
    stop_watch_loop();
  }
}
